package com.sys.controller;

import com.common.exception.BusinessException;
import com.common.util.FtpUtils;
import com.google.common.base.Strings;
import com.sys.model.CommonFile;
import com.sys.service.CommonFileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by yangjiabno on 2016/6/6.
 */
@Controller
@RequestMapping("common/file")
public class FileController {

    @Autowired
    private CommonFileService commonFileService;

    @Value("${file.path}")
    private String filePath="";

    @ResponseBody
    @RequestMapping(value = "/{fileid}",method = RequestMethod.GET)
    public CommonFile getFile(@PathVariable String fileid) {
        if(Strings.isNullOrEmpty(fileid)){
            throw new BusinessException("文件id不能为空");
        }
        CommonFile commonFile=commonFileService.selectById(fileid);
        return commonFile;
    }

    @ResponseBody
    @RequestMapping(value = "/upload",method = RequestMethod.POST)
    public CommonFile upLoad(MultipartFile upfile) throws IOException, NoSuchAlgorithmException {
        if(upfile==null){
            throw new BusinessException("文件上传为空");
        }
        //通过ftp上传
        CommonFile commonFile=commonFileService.upLoadFtp(upfile,filePath);
        return commonFile;
    }

    @RequestMapping("editor/upload")
    @ResponseBody
    public Map upload(MultipartFile imgFile) throws IOException, NoSuchAlgorithmException {
        if(imgFile==null){
            throw new BusinessException("文件上传为空");
        }
        CommonFile commonFile=commonFileService.upLoadFtp(imgFile, filePath);
        Map map = new HashMap();
        map.put("error", 0);
        map.put("url", "/common/file/load/img/"+commonFile.getId());
        return map;
    }

    @ResponseBody
    @RequestMapping(value = "/upload/more",method = RequestMethod.POST)
    public List<String> upLoad(MultipartFile[] files) throws IOException, NoSuchAlgorithmException {
        List<String> list=new ArrayList<>();
        if(files!=null&&files.length>0){
            for (int i=0;i<files.length;i++){
                //通过ftp上传
                CommonFile res=commonFileService.upLoadFtp(files[i],filePath);
                if(res!=null){
                    list.add(res.getId());
                }
            }
        }else {
            throw new BusinessException("文件上传为空");
        }
        return list;
    }

    @RequestMapping(value = "/download/{fileid}",method = RequestMethod.GET)
    public void downLoad(
            @PathVariable String fileid, HttpServletResponse response) throws IOException, NoSuchAlgorithmException {
        CommonFile commonFile=commonFileService.selectById(fileid);
        OutputStream out = response.getOutputStream();
        response.setContentType(commonFile.getFileType());
        response.setHeader("Content-Disposition", "attachment;fileName="
                + new String(commonFile.getFileName().getBytes("gbk"),"iso-8859-1"));
        FtpUtils.getInstanse().downloadFile(filePath,commonFile.getFilePath(),out);
        out.close();
        //得到文件存储路径
//        String path=multipartResolver.getFileItemFactory().getRepository().getPath();
//        InputStream inputStream = new FileInputStream(new File(SimpleConfig.get("file.path")+commonFile.getFilePath()));
//        byte[] b = new byte[2048];
//        int length;
//        while ((length = inputStream.read(b)) > 0) {
//            out.write(b, 0, length);
//        }
//        // 这里主要关闭。
//        out.close();
//        inputStream.close();
    }

    @RequestMapping(value = "/load/{fileid}",method = RequestMethod.GET)
    public void load(
            @PathVariable String fileid, HttpServletResponse response) throws IOException, NoSuchAlgorithmException {
        CommonFile commonFile=commonFileService.selectById(fileid);
        OutputStream out = response.getOutputStream();
        response.setContentType(commonFile.getFileType());
        FtpUtils.getInstanse().downloadFile(filePath,commonFile.getFilePath(),out);
        out.close();

        //得到文件存储路径
//        String path=multipartResolver.getFileItemFactory().getRepository().getPath();
//        InputStream inputStream = new FileInputStream(new File(SimpleConfig.get("file.path")+commonFile.getFilePath()));
//        byte[] b = new byte[2048];
//        int length;
//        while ((length = inputStream.read(b)) > 0) {.
//            out.write(b, 0, length);
//        }
        // 这里主要关闭。
//        out.close();
//        inputStream.close();
    }

    @RequestMapping(value = "/ngix/load/{fileid}",method = RequestMethod.GET)
    public String ngixLoad(
            @PathVariable String fileid, HttpServletResponse response) throws IOException, NoSuchAlgorithmException {
        CommonFile commonFile=commonFileService.selectById(fileid);
        if(commonFile==null){
            throw new BusinessException("文件不存在");
        }else {
             return "redirect:http://file.ip-cld.com/FtpFile/filepool/"+commonFile.getFilePath();
        }
    }

    @RequestMapping(value = "/load/img/{fileid}",method = RequestMethod.GET)
    public String loadImg(
            @PathVariable String fileid, HttpServletResponse response) throws IOException, NoSuchAlgorithmException {
        CommonFile commonFile=commonFileService.selectById(fileid);
        if(commonFile==null){
            throw new BusinessException("文件不存在");
        }else {
            return "redirect:http://file.ip-cld.com/ipdtfc_ftp/filePool/"+commonFile.getFilePath();
        }
    }
}
